<template>
    <div class="length-change-page">
        <!-- 标题与介绍 -->
        <ToolHeader :title="title" :subtitle="subtitle"/>

        <div class="content-box">
            <!-- 输入区域 -->
            <div class="input-group">
                <div class="input-item">
                    <span>选择单位：</span>
                    <el-select v-model="selectedUnit" placeholder="请选择单位" style="width: 100%;">
                        <el-option
                                v-for="unit in units"
                                :key="unit.value"
                                :label="unit.label"
                                :value="unit.value"
                        />
                    </el-select>
                </div>
                <div class="input-item">
                    <span>输入数值：</span>
                    <el-input
                            v-model="inputValue"
                            placeholder="请输入数值"
                    />
                </div>
            </div>

            <!-- 结果表格 -->
            <el-table
                    :data="tableData"
                    border
                    size="small"
                    style="width: 100%;"
            >
                <el-table-column
                        prop="label"
                        label="单位"
                        width="140"
                        :header-cell-style="{ backgroundColor: '#f0f0f0' }"
                        :cell-style="{ backgroundColor: '#f7f7f7', fontWeight: 'bold' }"
                >
                    <template #default="{ row }">
                        {{ row.label }}
                    </template>
                </el-table-column>
                <el-table-column
                        prop="value"
                        label="数值"
                >
                    <template #default="{ row }">
                        <el-input
                                v-model="row.value"
                                readonly
                                style="width: 100%;"
                        />
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script setup>
import {ref, onMounted, watch} from 'vue'
import {get, post} from '@/net/index.js'
import {ElMessage} from 'element-plus'
import ToolHeader from '@/components/ToolHeader.vue'
import {debounce} from 'lodash'

const title = ref('')
const subtitle = ref('')

const units = [
    {label: '毫米 (mm)', value: 'mm'},
    {label: '厘米 (cm)', value: 'cm'},
    {label: '分米 (dm)', value: 'dm'},
    {label: '米 (m)', value: 'm'},
    {label: '英寸 (in)', value: 'in'},
    {label: '英尺 (ft)', value: 'ft'},
    {label: '英里 (mi)', value: 'mi'},
]

const selectedUnit = ref('m')
const inputValue = ref('1')

const tableData = ref(
    units.map(unit => ({
        label: unit.label,
        value: ''
    }))
)

function loadInfo() {
    get(
        '/api/mathTool/getInfo?path=length_change',
        (data) => {
            if (data) {
                title.value = data.title || ''
                subtitle.value = data.introduction || ''
            }
        },
        (err) => {
            ElMessage.error('获取工具信息失败：' + err)
        }
    )
}

// 真实请求函数
function fetchLengthChangeResultNow() {
    if (!inputValue.value || isNaN(Number(inputValue.value))) {
        tableData.value = units.map(unit => ({
            label: unit.label,
            value: ''
        }))
        return
    }
    const params = {
        type: selectedUnit.value,
        text: inputValue.value
    }
    post('/api/mathTool/getLengthChangeResult', params,
        (data) => {
            if (Array.isArray(data)) {
                tableData.value = data.map(item => ({
                    label: item.label,
                    value: item.value
                }))
            } else {
                ElMessage.error('返回数据格式错误')
            }
        },
        (msg) => {
            ElMessage.error('获取长度换算失败: ' + msg)
        }
    )
}

// 防抖函数（500ms）
const debouncedFetch = debounce(fetchLengthChangeResultNow, 500)

// 监听输入值和单位变化，触发防抖请求
watch([inputValue, selectedUnit], () => {
    debouncedFetch()
})

// onMounted 时调用防抖请求（首次也延迟500ms）
onMounted(() => {
    loadInfo()
    debouncedFetch()
})
</script>


<style scoped>
.length-change-page {
    width: 100%;
    padding: 1rem;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.content-box {
    width: 100%;
    max-width: 30rem;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
}

.input-group {
    display: flex;
    gap: 1rem;
}

.input-item {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.input-item span {
    margin-bottom: 0.4rem;
    font-weight: 500;
}
</style>